﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NewsProgram.Models
{
    public class NewsRepository 
    {
        private List<NewsItem> m_news = new List<NewsItem>();
        NewsDBDataContext db = new NewsDBDataContext();


        public IEnumerable<NewsItem> getAllNews()
        {
            var result = (from news in db.NewsItems
                          select news);

            return result;
        }

        public IEnumerable<NewsItem> getTop10News()
        {
            //IEnumerable<NewsItem> result = (from news in db.NewsItems
            //                                where news.
            var result = (from news in db.NewsItems.Take(10)
                          orderby news.ID descending
                          select news);
    
            return result;
        }


        public NewsItem getNewsByID(int id)
        {
            var result = (from news in db.NewsItems
                    where news.ID == id
                    select news).SingleOrDefault();

            return result;
        }

        public void addNews ( NewsItem n )
        {
            db.NewsItems.InsertOnSubmit(n);
            db.SubmitChanges();
        }


        public void updateNews( NewsItem n )
        {

            var oldNews = getNewsByID(n.ID);
            if (oldNews != null)
            {
                oldNews.NewsText = n.NewsText;
                oldNews.Title = n.Title;
                oldNews.Category = n.Category;
                oldNews.DateAdded = n.DateAdded;
                db.SubmitChanges();
            }
            //Kasta villu eitthvað fór úrskeiðis...
    
        }


    }

}
